"""
用户相关模型
===========
定义用户管理相关的所有数据模型
"""

from typing import Optional, List
from datetime import datetime
from pydantic import Field, EmailStr, validator
from .base_model import BaseModel, UUIDMixin, TimestampMixin, SoftDeleteMixin
from .enums import UserStatus, UserRole


class UserAuth(BaseModel):
    """用户认证信息"""
    
    username: str = Field(
        description="用户名",
        min_length=3,
        max_length=50,
        example="john_doe"
    )
    
    password: str = Field(
        description="密码",
        min_length=8,
        max_length=128,
        example="SecurePassword123!"
    )


class UserCreate(BaseModel):
    """创建用户请求"""
    
    username: str = Field(
        description="用户名",
        min_length=3,
        max_length=50,
        example="john_doe"
    )
    
    email: EmailStr = Field(
        description="邮箱地址",
        example="john@example.com"
    )
    
    password: str = Field(
        description="密码",
        min_length=8,
        max_length=128,
        example="SecurePassword123!"
    )
    
    first_name: Optional[str] = Field(
        default=None,
        description="名",
        max_length=50,
        example="John"
    )
    
    last_name: Optional[str] = Field(
        default=None,
        description="姓",
        max_length=50,
        example="Doe"
    )
    
    phone: Optional[str] = Field(
        default=None,
        description="手机号",
        example="+1234567890"
    )
    
    @validator('username')
    def validate_username(cls, v):
        if not v.replace('_', '').replace('-', '').isalnum():
            raise ValueError('用户名只能包含字母、数字、下划线和连字符')
        return v


class UserUpdate(BaseModel):
    """更新用户请求"""
    
    email: Optional[EmailStr] = Field(
        default=None,
        description="邮箱地址"
    )
    
    first_name: Optional[str] = Field(
        default=None,
        description="名",
        max_length=50
    )
    
    last_name: Optional[str] = Field(
        default=None,
        description="姓",
        max_length=50
    )
    
    phone: Optional[str] = Field(
        default=None,
        description="手机号"
    )
    
    status: Optional[UserStatus] = Field(
        default=None,
        description="用户状态"
    )


class UserProfile(BaseModel):
    """用户公开信息"""
    
    user_id: str = Field(description="用户ID")
    username: str = Field(description="用户名")
    first_name: Optional[str] = Field(description="名")
    last_name: Optional[str] = Field(description="姓")
    avatar_url: Optional[str] = Field(description="头像URL")
    bio: Optional[str] = Field(description="个人简介")
    created_at: datetime = Field(description="创建时间")
    
    @property
    def full_name(self) -> str:
        """全名"""
        if self.first_name and self.last_name:
            return f"{self.first_name} {self.last_name}"
        return self.first_name or self.last_name or self.username


class User(UUIDMixin, TimestampMixin, SoftDeleteMixin):
    """用户完整信息"""
    
    username: str = Field(
        description="用户名",
        min_length=3,
        max_length=50
    )
    
    email: EmailStr = Field(
        description="邮箱地址"
    )
    
    password_hash: str = Field(
        description="密码哈希"
    )
    
    first_name: Optional[str] = Field(
        default=None,
        description="名",
        max_length=50
    )
    
    last_name: Optional[str] = Field(
        default=None,
        description="姓",
        max_length=50
    )
    
    phone: Optional[str] = Field(
        default=None,
        description="手机号"
    )
    
    avatar_url: Optional[str] = Field(
        default=None,
        description="头像URL"
    )
    
    bio: Optional[str] = Field(
        default=None,
        description="个人简介",
        max_length=500
    )
    
    status: UserStatus = Field(
        default=UserStatus.PENDING,
        description="用户状态"
    )
    
    roles: List[UserRole] = Field(
        default_factory=lambda: [UserRole.TRADER],
        description="用户角色列表"
    )
    
    email_verified: bool = Field(
        default=False,
        description="邮箱是否已验证"
    )
    
    phone_verified: bool = Field(
        default=False,
        description="手机号是否已验证"
    )
    
    last_login_at: Optional[datetime] = Field(
        default=None,
        description="最后登录时间"
    )
    
    login_count: int = Field(
        default=0,
        description="登录次数"
    )
    
    def to_profile(self) -> UserProfile:
        """转换为公开信息"""
        return UserProfile(
            user_id=self.id,
            username=self.username,
            first_name=self.first_name,
            last_name=self.last_name,
            avatar_url=self.avatar_url,
            bio=self.bio,
            created_at=self.created_at
        )
    
    def has_role(self, role: UserRole) -> bool:
        """检查是否具有特定角色"""
        return role in self.roles
    
    def add_role(self, role: UserRole):
        """添加角色"""
        if role not in self.roles:
            self.roles.append(role)
    
    def remove_role(self, role: UserRole):
        """移除角色"""
        if role in self.roles:
            self.roles.remove(role)
    
    def update_login(self):
        """更新登录信息"""
        self.last_login_at = datetime.utcnow()
        self.login_count += 1
